﻿using System.Web.Mvc;
using MvcBlog.Common.Models;
using MvcBlog.ViewModels;
using System.Web.Security;
using System.Security.Principal;
using System;

namespace MvcBlog.Controllers
{
    public class LoginController : Controller
    {

        LoginDataAccess userDB;

        //constructor
        public LoginController()
        {
            var con = ConnectionFactory.getConnection();
            userDB = new LoginDataAccess(con);
        }

        

        //call formular
        public ActionResult Index(string returnUrl)
        {
            if (String.IsNullOrEmpty(returnUrl)
                && Request.UrlReferrer != null
                && Request.UrlReferrer.ToString().Length > 0)
            {
                return RedirectToAction("Index",
                    new { returnUrl = Request.UrlReferrer.ToString() });
            }

            return View();
        }

        //do authentication
        [HttpPost]
        public ActionResult Index(LoginViewModel lData, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = userDB.getUserByName(lData.UserName);

                bool UserAuthenticated = Authenticate(user, lData.Password);

                LoginViewModel viewModel = new LoginViewModel(user, UserAuthenticated);

                if (UserAuthenticated == true)
                {
                    //redirect zur url von der login aufgerufen wurde, falls referrer vorhanden
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }

                }
                else if (user != null && !user.Activated)
                {
                    //aktivierung ausständig
                    ModelState.AddModelError("Username", "Ihr Benutzername ist noch nicht aktiviert worden.");
                    ModelState.AddModelError("Password", "");
                    return View(lData);
                }
                else
                {   //falscher username/Passwort
                    ModelState.AddModelError("UserName", "Falscher Benutzername oder Passwort.");
                    ModelState.AddModelError("Password", "");
                    return View(viewModel);
                }
            }
            else
            {
                //formular nicht komplett ausgefüllt
                return View(lData);
            }
        }

        public ActionResult LogOff()
        {
            RemoveAuthCookie(HttpContext.User.Identity.Name);
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ForgetPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgetPassword(LoginViewModel vm)
        {
            vm.Password = userDB.getUserByName(vm.UserName).Password;
            return View(vm);
        }

        public ActionResult Password()
        {
            return View();
        }

        //authenticate
        public bool Authenticate(User user, string password)
        {
            if (user != null && user.Password == password && user.Activated)
            {
                SetAuthenticationCookie(user.Username);
                return true;
            }
            else
            {
                return false;
            }
        }

        public virtual void SetAuthenticationCookie(string username)
        {
            FormsAuthentication.SetAuthCookie(username, false);
            //TODO Rollen des Benutzers auslesen
            string[] roles = new string[] { "Role1", "Role2" };
            

            HttpContext.User = new GenericPrincipal(new GenericIdentity(username), roles);

        }

        public virtual void RemoveAuthCookie(string username)
        {
            FormsAuthentication.SignOut();
            HttpContext.User = null;
        }

    }
}
